import java.io.BufferedWriter;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.JTextArea;

/*
 * TCSS 422 Process Control Simulator
 * Group Money: Al McKenzie, Michael Pitts, Taylor Zielske
 */

/**
 * Allows streaming output to a given JTextArea.
 * @author Michael Pitts
 * @version Dec 8, 2011
 */
public class TextOutStream extends OutputStream {
	
	/** Default output file. */
	private static final String OUT_FILE = "output.txt";
	
	/** The text area to stream to. */
	private final JTextArea my_text_area;
	
	/** Output to file. */
	private BufferedWriter my_out_to_file;

	/**
	 * Creates a new OutputStream that outputs to the given JTextArea.
	 * @param the_text_area is who is to receive the output text stream.
	 */
	public TextOutStream(final JTextArea the_text_area) {
		my_text_area = the_text_area;
		try {
			my_out_to_file = new BufferedWriter(new FileWriter(OUT_FILE));
		} catch (IOException e) {
			my_out_to_file = null; // no file output
		}
	}

	@Override public void write(final int the_byte) {
		if (Character.isDefined((char) the_byte)) {
			my_text_area.append(String.valueOf((char) the_byte));
			if (my_out_to_file != null) {
				try {
					my_out_to_file.append((char) the_byte);
					my_out_to_file.flush();
				} catch (IOException e) {
					// Don't write character
				}
			}
		}
	}
	
	/**
	 * Gets a new PrintStream object that writes to the underlying JTextArea.
	 * @return a new PrintStream that outputs to the underlying JTextArea.
	 */
	public PrintStream getStream() {
		return new PrintStream(this);
	}

	@Override public void close() {
		if (my_out_to_file != null) {
			try {
				my_out_to_file.flush();
				my_out_to_file.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		try {
			super.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
}
